package com.bestcem.xm.ticket.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.dingtalkapp.grpc.v1.services.DingtalkAppServiceGrpc;
import com.bestcem.xm.dingtalkapp.grpc.v1.services.SendMsgByTemplateRequest;
import com.bestcem.xm.dingtalkapp.grpc.v1.services.SendMsgByTemplateResponse;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import zhongyan.xm.base.v1.Base;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Objects;

/**
 * 钉钉模块 grpc client 方法
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/12/6 10:49
 */
@Slf4j
@Service
public class TicketDingTalkGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private DingtalkAppServiceGrpc.DingtalkAppServiceBlockingStub dingtalkAppServiceBlockingStub;

    /**
     * 发送钉钉模板消息
     *
     * @param userIds    接收消息的倍市得userId列表
     * @param templateId 钉钉模板id
     * @param params     钉钉模板自定义参数
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/12/6 10:43
     */
    public void sendTemplateMessage(@Nonnull Collection<String> userIds, @Nonnull String templateId, @Nullable String params) {
        SendMsgByTemplateRequest.Builder builder = SendMsgByTemplateRequest.newBuilder();
        if (!CollectionUtils.isEmpty(userIds)) {
            builder.addAllUserIds(userIds);
        }
        builder.setTemplateId(templateId);
        if (!ObjectUtils.isEmpty(params)) {
            builder.setData(params);
        }
        try {
            SendMsgByTemplateResponse response = dingtalkAppServiceBlockingStub.sendMsgByTemplate(builder.buildPartial());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] DINGTALK sendTemplateMessage {}-{}-{} Error; ErrorMsg: {}",
                        userIds, templateId, params, response);
            }
        } catch (Exception e) {
            log.error("[Ticket] DINGTALK sendTemplateMessage {}-{}-{} Error",
                    userIds, templateId, params, e);
        }
    }
}
